package com.gitee.wsl.platform.thread.task

import java.time.Duration
import java.util.concurrent.CountDownLatch
import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import kotlin.test.assertTrue

object TimedAwait {
    var TIMEOUT: Duration? = null

    init {
        if (System.getenv("CI") != null) TIMEOUT = Duration.ofSeconds(20)
        else TIMEOUT = Duration.ofSeconds(10)
    }

    @Throws(InterruptedException::class)
    fun latchNoExpectations(latch: CountDownLatch) {
        latch.await(TIMEOUT!!.toMillis(), TimeUnit.MILLISECONDS)
    }

    @JvmOverloads
    @Throws(InterruptedException::class)
    fun latchAndExpectCompletion(latch: CountDownLatch, name: String = "latch") {
        assertTrue(
            latch.await(TIMEOUT!!.toMillis(), TimeUnit.MILLISECONDS),
            "$name.await"
        )
    }

    @Throws(InterruptedException::class, TimeoutException::class)
    fun future(future: Future<*>) {
        try {
            future[TIMEOUT!!.toMillis(), TimeUnit.MILLISECONDS]
        } catch (e: ExecutionException) {
            throw RuntimeException(e)
        }
    }
}
